#include <Arduino.h>
#include <ESP8266WiFiMulti.h>
#include <IRsend.h>
#include <DHT.h>
#include "signal_sender.h"
#include "api_client.h"

//#define DEV

#ifdef DEV
    #include "key_dev.h"
#else
    #include "key_deploy.h"
#endif

const int dht_pin = 12;   // wemos D12
const int sig_pin = 0;      // D8

ESP8266WiFiMulti WiFiMulti;
DHT dht(dht_pin, DHT11);
ApiClient api(SERVER_ADDR, CLIENT_ID, CLIENT_TOKEN);
SignalSender sigSender(sig_pin);

int wifi_is_conn(){
    if ((WiFiMulti.run() != WL_CONNECTED)) {
        Serial.printf("wifi not conn, ret=%d\n", WiFiMulti.run());
        return -1;
    }
    return 0;
}


// 获取湿度
int get_humi(){
  float humi = dht.readHumidity();
  if (isnan(humi)) {
    Serial.println("Failed to read from DHT sensor!");
    return 0;
  }
  return humi;
}

// 获取温度
int get_temp(){
  float temp = dht.readTemperature();
  if (isnan(temp)) {
    Serial.println("Failed to read from DHT sensor!");
    return 0;
  }
  return temp;
}

void switch_aircond(boolean open){
    if(open){
        sigSender.send_sig(1);
        Serial.println("open aircond");
    }else{
        sigSender.send_sig(2);
        Serial.println("close aircond");
    }
}

void setup() {
  Serial.begin(9600);
  Serial.println("setup begin");
  // USE_SERIAL.setDebugOutput(true);
  dht.begin();
  WiFi.mode(WIFI_STA);
  pinMode(LED_BUILTIN, OUTPUT);
  WiFiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
  Serial.println("setup finish");
}

void flash_led(int l, int s){
    for(int i=0; i<l; i++){
        digitalWrite(LED_BUILTIN, LOW);
        delay(300);
        digitalWrite(LED_BUILTIN, HIGH);
        delay(100);

    }
    for(int i=0; i<s; i++){
        digitalWrite(LED_BUILTIN, LOW);
        delay(50);
        digitalWrite(LED_BUILTIN, HIGH);
        delay(100);
    }
}

void loop() {
    if(wifi_is_conn() != 0){
        flash_led(0, 3);
        delay(1000*1);
        return;
    }
    int t = get_temp();
    int h = get_humi();
    Serial.printf("temp=%d humi=%d\n", t, h);
    String value;
    if(api.sync_data(value, h, t) != 0){
        Serial.println("get_cmd fail");
        flash_led(0, 2);
        flash_led(1, 0);
        delay(1000*3);
        return;
    }
    if(value == "empty"){
        // do nothing
    }else if( value == "on"){
        switch_aircond(true);
        flash_led(1, 2);
    }else if( value == "off"){
        switch_aircond(false);
        flash_led(1, 1);
    }else{
        Serial.println("unknow cmd=" + value);
    }
}

